import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import router from '@/router'
import { config as appConfig } from '@/config'
import { log } from './logger'
import { handleError, ErrorType } from './error-handler'

// 定义 API 响应接口
export interface ApiResponse<T = any> {
  data: T
  message?: string
  error?: string
  details?: Array<{
    msg: string
    param: string
    location: string
  }>
  pagination?: {
    total: number
    page: number
    limit: number
  }
}

// 扩展请求配置类型
interface RetryConfig extends InternalAxiosRequestConfig {
  retryCount?: number
  retryDelay?: number
}

// 创建 axios 实例
const axiosInstance: AxiosInstance = axios.create({
  baseURL: appConfig.apiBaseUrl,
  timeout: appConfig.timeout,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config: RetryConfig) => {
    // 添加重试计数
    config.retryCount = 0
    config.retryDelay = appConfig.retryConfig.retryDelay
    
    // 从 localStorage 获取 token
    const token = localStorage.getItem('admin_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 记录请求日志
    log.debug('API 请求', {
      method: config.method?.toUpperCase(),
      url: config.url,
      data: config.data,
      params: config.params
    }, 'API')
    
    return config
  },
  (error) => {
    log.error('API 请求错误', error, 'API')
    return Promise.reject(error)
  }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    // 记录响应日志
    log.debug('API 响应成功', {
      url: response.config.url,
      method: response.config.method,
      status: response.status,
      dataSize: JSON.stringify(response.data).length
    }, 'API')
    return response
  },
  async (error) => {
    const config = error.config as RetryConfig
    
    // 记录详细的错误信息
    log.error('API错误', {
      url: config?.url,
      method: config?.method,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      requestData: config?.data
    }, 'API')
    
    // 特别处理400错误，显示详细的验证错误信息
    if (error.response?.status === 400 && error.response?.data) {
      console.group('🔍 400错误详细信息')
      console.log('错误数据:', error.response.data)
      console.log('请求URL:', config?.url)
      console.log('请求方法:', config?.method)
      console.log('请求数据:', config?.data)
      if (error.response.data.details) {
        console.log('验证错误详情:', error.response.data.details)
      }
      if (error.response.data.error) {
        console.log('错误信息:', error.response.data.error)
      }
      console.groupEnd()
    }
    
    // 处理 429 错误（请求过多）- 自动重试
    if (error.response?.status === 429) {
      if (config?.retryCount && config.retryCount < appConfig.retryConfig.maxRetries) {
        config.retryCount++
        
        // 使用指数退避策略
        const delay = (config.retryDelay || appConfig.retryConfig.retryDelay) * Math.pow(2, config.retryCount - 1)
        log.warn(`请求被限流，${delay}ms后重试 (${config.retryCount}/${appConfig.retryConfig.maxRetries})`, 
          { url: config.url }, 'API')
        
        await new Promise(resolve => setTimeout(resolve, delay))
        return axiosInstance(config)
      }
    }
    
    // 处理 401 错误（未授权）- 自动跳转登录
    if (error.response?.status === 401) {
      localStorage.removeItem('admin_token')
      router.push('/login')
    }
    
    // 统一错误处理，不在这里显示消息，由具体的调用方处理
    const appError = handleError.api(error, 'API')
    return Promise.reject(appError)
  }
)

// API 客户端类
class ApiClient {
  private client: AxiosInstance

  constructor(client: AxiosInstance) {
    this.client = client
  }

  // 通用请求方法
  private async request<T = any>(config: AxiosRequestConfig): Promise<ApiResponse<T>> {
    try {
      const response = await this.client.request<ApiResponse<T>>(config)
      return response.data
    } catch (error) {
      throw error
    }
  }

  // GET 请求
  async get<T = any>(url: string, params?: any): Promise<ApiResponse<T>> {
    return this.request<T>({
      method: 'GET',
      url,
      params
    })
  }

  // POST 请求
  async post<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>({
      method: 'POST',
      url,
      data
    })
  }

  // PUT 请求
  async put<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>({
      method: 'PUT',
      url,
      data
    })
  }

  // DELETE 请求
  async delete<T = any>(url: string): Promise<ApiResponse<T>> {
    return this.request<T>({
      method: 'DELETE',
      url
    })
  }

  // 文件上传
  async upload<T = any>(url: string, formData: FormData): Promise<ApiResponse<T>> {
    try {
      const response = await this.client.request<ApiResponse<T>>({
        method: 'POST',
        url,
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      return response.data
    } catch (error) {
      throw error
    }
  }
}

export const api = new ApiClient(axiosInstance)

// 从配置文件导入API端点
export { apiEndpoints as API_ENDPOINTS } from '@/config' 